package top.zhangjianyong.tools.config.json;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;

/**
 * @author ： zhangjianyong
 * @date ： 2021/5/13 14:55
 */
@Configuration
public class FastJsonMessageConfig {

    //配置fastjson进行消息转换
    @Bean
    public HttpMessageConverters fastjsonHttpMessageConverters() {
        //创建FastJson消息转换器
        FastJsonHttpMessageConverter2 converter = new FastJsonHttpMessageConverter2();
        //创建配置对象
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //配置序列化进行格式化json数据
        // config.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        //配置序列化器
        SerializeConfig serializeConfig = SerializeConfig.getGlobalInstance();
        serializeConfig.put(YearMonth.class, new LocalDateTimeToStringSerializer("yyyy-MM"));
        serializeConfig.put(LocalDate.class, new LocalDateTimeToStringSerializer("yyyy-MM-dd"));
        serializeConfig.put(LocalDateTime.class, new LocalDateTimeToStringSerializer("yyyy-MM-dd HH:mm:ss"));
        fastJsonConfig.setSerializeConfig(serializeConfig);
        //将此配置传给转换器
        converter.setFastJsonConfig(fastJsonConfig);

        //微信消息需要解析xml
        MappingJackson2XmlHttpMessageConverter xmlConverter = new MappingJackson2XmlHttpMessageConverter();
        //通过构造方法传递对象
        return new HttpMessageConverters(converter, xmlConverter);

    }

    public static void main(String[] args) {
        YearMonth now = YearMonth.now();
        System.out.println(JSONObject.toJSONString(now));
    }

}
